package cn.j2e.login.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cpms.dto.LoginUser;

import cn.j2e.login.service.iter.ILoginService;
import cn.j2e.security.CookieUtils;
import cn.j2e.security.LogonContext;
import cn.j2web.core.exceptions.LoginException;

@Controller
public class LogonController {
	
	private static Logger log = LoggerFactory.getLogger(LogonController.class);
	
	@Resource(name="loginService")
	private ILoginService loginService;
	
	@RequestMapping(value="/login")
	public ModelAndView login(LoginUser user,HttpServletRequest req,HttpServletResponse resp){
		log.debug("login");
		return doLogin(user,req,resp);
	}
	
	private ModelAndView doLogin(LoginUser user,HttpServletRequest req,HttpServletResponse resp){
		ModelAndView mav =null;
		try {
			//判断当前登陆用户 cookie 是否存在。
			if(!checkCookieUser(req, resp)){//  不存在的话，跳到登陆页面。
				if (StringUtils.isEmpty(user.getUserName())
						&& StringUtils.isEmpty(user.getPassWord())
						&& StringUtils.isEmpty(user.getValidCode())) {
						mav = new ModelAndView(this.loginService.getLoginJspView());
				}else{
					if(this.validCode(user,req)){
						log.debug(" the  system validate the validCode is passed ");
						if(this.validUser(user,req,resp)){
							mav = new ModelAndView(this.loginService.getMainJspView());
						}else{
							mav = new ModelAndView(this.loginService.getLoginJspView());
						}
					}
				}
			}else{// 存在的话跳到主页面。
				mav = new ModelAndView(this.loginService.getMainJspView());
			}
		} catch (Exception e) {
			mav = new ModelAndView(this.loginService.getLoginJspView());
			mav.addObject("loginException", e.getMessage());
			log.error("loginException",e);
		}
		return mav;
	}
	
	private boolean validCookieUser(LoginUser user,HttpServletRequest req,HttpServletResponse resp)throws LoginException{
		 try {
			 LoginUser lu = LogonContext.getInstance().getLoginUser(req.getSession().getId());
			 if(lu !=null &&  lu.getStatus()==LoginUser.loginStatuEnum.LOGIN_SUCCESS){
				 return true;
			 };
			 //验证cookie 用户信息。
		} catch (Exception e) {
			throw new LoginException(e.getMessage());
		}
		return false;
	}
	
	private boolean validUser(LoginUser user,HttpServletRequest req,HttpServletResponse resp)throws LoginException{
		 try {
			   if(user.getUserName()==null)
					throw new LoginException("登陆名为空");
				if(user.getPassWord()==null)
					throw new LoginException("密码为空");
				LoginUser loginUser = loginService.getLoginUser(user);
				// 验证密码
			if (loginUser.getStatus() == LoginUser.loginStatuEnum.LOGIN_SUCCESS) {
					LogonContext.getInstance().addLoginUser(req.getSession().getId(), loginUser);
					CookieUtils.write(req, resp, user.getUserName(),user.getPassWord(), this.loginService.getIsSavePasswordToCookie());
					return true;
				}else{
					throw new LoginException("用户信息不正确！ ");
				}
		} catch (Exception e) {
			throw new LoginException(e.getMessage());
		}
	}
	
	
	private boolean validCode(LoginUser user,HttpServletRequest req) throws  LoginException{
		String validCode = user.getValidCode();
		if(null!=validCode){
			// todo 完善验证码的校验功能。 
			String randValid = (String) req.getSession().getAttribute(this.loginService.getValidKey());
			if(validCode.equals(randValid)){
				return true;
			}
			throw new LoginException("验证码错误！");
		}else{
			throw new LoginException("请输入验证码！");
		}
	}

	private boolean checkCookieUser(HttpServletRequest req,HttpServletResponse resp){
		boolean isSavePasswordToCookie =	this.loginService.getIsSavePasswordToCookie();
		log.debug("isSavePasswordToCookie:"+isSavePasswordToCookie);
		if(isSavePasswordToCookie){// 当密码写入cookie时，验证cookie的用户。
			//读出来的cookie信息为空。
			com.cpms.dto.LoginUser loginUser = CookieUtils.read(req, resp,isSavePasswordToCookie);
			if(StringUtils.isEmpty(loginUser.getUserName()))return false;
			if(this.validCookieUser(loginUser,req,resp)){
				log.debug(" cookie user is checked !");
				return true;
			}else{
				log.debug(" cookie user is not checked !");
				return false;
			}
		}
		log.debug(" cookie user is not checked !");
		return false;
	}
	
	public ILoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}
	
}
